<template>
  <div class="callTipDialogDiv">
    <el-dialog
      append-to="callTipDialogDiv"
      v-model="dialogVisible"
      title="Tips"
      width="320"
      draggable
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
      :fullscreen="false"
    >
      <template #header>
        <div class="flex justify-between font-size-12px text-inherit">
          <div>通话小贴片[可拖动]</div>
          <ElDropdown trigger="click" @command="setPhoneMode">
            <div class="phone-icon-box">
              <Icon :size="12" class="!p-0" icon="fa:phone" />
              <div class="phone-icon-text ml-4px <lg:hidden">
                <span v-if="!phoneMode">选择话机</span>
                <span v-else>{{ phoneModeMap[phoneMode] }}</span>
              </div>
            </div>
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem
                  v-for="item in phoneModeList"
                  :key="item.value"
                  :command="item.value"
                >
                  {{ item.name }}
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
          <div class="cursor-pointer text-#337ecc">
            <span @click="close"
              ><el-icon><CloseBold /></el-icon
            ></span>
          </div>
        </div>
      </template>
      <ContentWrap v-if="!data" class="content mt-15px">暂无通话</ContentWrap>

      <ContentWrap v-else class="content mt-15px">
        <div class="flex flex-col items-center justify-between">
          <div class="flex items-center justify-between">
            <div
              class="flex items-center px-20px py-5px text-white"
              style="border-radius: 24px"
              :style="{ background: statusCom[data.status]?.color }"
            >
              <Icon :icon="statusCom[data.status]?.icon" class="mr-4px"></Icon>
              {{ statusMap[data.status] }}
            </div>
            <div class="ml-10px cursor-pointer" v-if="showHangup">
              <el-text type="danger" @click="onHangup">挂断</el-text>
            </div>
          </div>
          <p class="text-22px font-700 !my-10px">{{ data.callee }}</p>
          <div class="flex justify-left">
            <el-text class="text-14px text-coolGray">{{
              (customerInfo && customerInfo.name) || '-'
            }}</el-text>
          </div>
          <el-divider style="margin: 8px 0 12px; border-color: #fff; border-top-style: dashed" />

          <!-- <el-divider /> -->
          <!-- <div>
            <el-button>呼叫失败</el-button>
            <el-button type="primary" :icon="Phone">呼叫</el-button>
          </div> -->
        </div>
        <el-descriptions v-if="customerInfo" :column="1" class="transparent">
          <el-descriptions-item label="最后跟进时间:">{{
            (customerInfo && formatDate(customerInfo.lastFollowTime)) || '-'
          }}</el-descriptions-item>
          <el-descriptions-item label="最后跟进内容:">{{
            (customerInfo && customerInfo.lastFollowRecord) || '-'
          }}</el-descriptions-item>
        </el-descriptions>
        <el-divider style="margin: 8px 0 12px; border-color: #fff; border-top-style: dashed" />
        <div class="position-relative" v-if="customerInfo">
          <el-input
            v-model="followUp"
            :rows="3"
            maxlength="80"
            type="textarea"
            placeholder="输入跟进内容,可输入80个字符。"
            show-word-limit
          >
          </el-input>
        </div>
        <div class="flex gap-4 mb-4" style="margin-top: 10px; align-items: center">
          <span style="flex-shrink: 0; font-size: 12px">下次联系时间</span>
          <el-date-picker v-model="nextTime" placeholder="选择时间" type="date" value-format="x" />
        </div>
        <div class="card-btn">
          <el-button :disabled="isSumit" @click="saveFollow" type="primary" size="small"
            >保存跟进</el-button
          >
        </div>
        <div v-if="customerInfo" :class="data.source == 'clue' ? 'card-btns' : 'card-btn'">
          <el-button
            size="small"
            @click="setTag"
            plain
            v-if="data.source == 'clue' || data.source == 'customer'"
            >修改标签</el-button
          >
          <el-button
            @click="transCustomer"
            size="small"
            plain
            v-if="data.source == 'clue' || data.source == 'ent'"
            >转客户</el-button
          >
          <!--
            <el-button
            size="small"
            plain
            @click="updateCustomerLevel"
            v-if="data.source == 'customer'"
            >修改客户级别</el-button
            >
          -->
        </div>
      </ContentWrap>
    </el-dialog>
  </div>
  <!-- clue标签弹窗 -->
  <EditTagForm ref="editTagForm" :moduleId="crmStore.getModuleId" />

  <!-- customer客户标签-->
  <EditTagCustomerForm ref="editTagCustomerForm" :moduleId="crmStore.getModuleId" />

  <!-- ent转客户-->
  <CustomerForm ref="customerFormRef" />

  <!--<EditTagEntForm ref="editTagEnt" />-->

  <Dialog v-model="visibleFrom" title="修改客户级别">
    <div>
      <el-form ref="formRef" label-width="100px">
        <el-form-item label="客户级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择客户级别" class="w-1/1">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_LEVEL)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> </el-form
    ></div>
    <template #footer>
      <el-button @click="visibleFrom = false">取 消</el-button>
      <el-button type="primary" @click="confrimCustomer">确 定</el-button>
    </template>
  </Dialog>
  <audio :src="audioUrl" ref="audio" loop></audio>
</template>

<script setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CloseBold } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/formatTime'
import { usePhoneStore } from '@/store/modules/phone'
import * as AgentApi from '@/api/call/agent'
import WebPhone from '@/hooks/web/useCall'
import EditTagForm from '@/views/crm/clue/editTagForm/index.vue'
import EditTagCustomerForm from '@/views/crm/customer/editTagForm/index.vue'
import EditTagEntForm from '@/views/ent/receivedata/editTagForm/index.vue'
import * as CustomerApi from '@/api/crm/customer'
import * as ClueApi from '@/api/crm/clue'
import CustomerForm from '@/views/crm/customer/CustomerForm.vue'
import { useCrmStore } from '@/store/modules/crm'
import audioUrl from '@/assets/audio/preview.mp3'
import log from '@/utils/log'
import * as LevelApi from '@/api/crm/customerTagConfig'

defineOptions({ name: 'CallTips' })

const audio = ref(null)

const levelOptions = ref([]) //客户级别
const resultLevel = ref([])
const visibleFrom = ref(false)
const crmStore = useCrmStore()
const formData = ref({
  level: ''
})
const editTagForm = ref(null)
const editTagCustomerForm = ref(null)
const editTagEnt = ref(null)
const message = useMessage()
const followUp = ref('')
const nextTime = ref('')
const reqNo = ref(null)
const number = ref(null)
const customerInfo = ref(null)
const dialogVisible = ref(false)
const useStore = usePhoneStore()
const statusMap = {
  ringing: '呼叫中',
  progress: '呼叫中',
  accepted: '正在通话',
  reject: '拒接',
  cancel: '已挂断',
  failed: '呼叫失败',
  ended: '已挂断',
  missed: '系统繁忙'
}
const phoneModeMap = {
  sip: 'SIP话机',
  recall: '双向回拨',
  box: '话机盒子',
  sim: '手机SIM卡'
}
const phoneModeList = [
  {
    name: 'SIP话机',
    value: 'sip'
  },
  {
    name: '双向回拨',
    value: 'recall'
  },
  {
    name: '话机盒子',
    value: 'box'
  },
  {
    name: '手机SIM卡',
    value: 'sim'
  }
]
const statusCom = {
  ringing: {
    icon: 'ep:phone',
    color: '#0052cc'
  },
  progress: {
    icon: 'ep:phone',
    color: '#0052cc'
  },
  accepted: {
    icon: 'ep:microphone',
    color: '#67C23A'
  },
  reject: {
    icon: 'ep:remove',
    color: '#F56C6C'
  },
  cancel: {
    icon: 'ep:switch-button',
    color: '#E6A23C'
  },
  failed: {
    icon: 'ep:remove',
    color: '#F56C6C'
  },
  ended: {
    icon: 'ep:switch-button',
    color: '#E6A23C'
  },
  missed: {
    icon: 'ep:refresh-right',
    color: '#909399'
  }
}
const data = computed(() => {
  console.info(' ----- session ---- ', useStore)
  return useStore.session || null
})
const isSumit = computed(() => {
  return followUp.value == ''
})
const open = async () => {
  if (data.value) {
    if (reqNo.value != data.value.reqNo) {
      // 这是一个新的请求
      // 获取customerInfo
      customerInfo.value = await AgentApi.getCustomerInfo({ reqNo: data.value.reqNo })
    }
    reqNo.value = data.value.reqNo
    number.value = data.value.callee
  }
  // 客户级别
  // levelOptions.value = resultLevel.value = await LevelApi.getLevelSimple()
  if (!dialogVisible.value) {
    phoneMode.value = useStore.getPhoneMode
    dialogVisible.value = true
  }
}
const phoneMode = ref(null)
const audioConstraints = {
  video: false,
  audio: {
    noiseSuppression: true,
    echoCancellation: true
  },
  logicalSurface: false
}
/*选择模式*/
const setPhoneMode = async (pm) => {
  try {
    if (pm == 'sip') {
      await navigator.mediaDevices.getUserMedia(audioConstraints)
    }
  } catch {
    ElMessage.warning('未识别到麦克风,请检查麦克风')
    return
  }
  await useStore.setPhoneMode(pm)
  phoneMode.value = pm
  // TODO  调用getChannelId方法，验证话机模式是否激活
  WebPhone.getInstance().reg()
}
/*修改客户级别*/
const updateCustomerLevel = () => {
  visibleFrom.value = true
}
/*确定修改客户级别*/
const confrimCustomer = async () => {
  let obj = {
    id: data.value.sourceId,
    level: formData.value.level
  }
  const res = await CustomerApi.updateCustomerWeCom(obj)
  visibleFrom.value = false
  ElMessage.success('操作成功')
}
const customerFormRef = ref(null)
/*转客户*/
const transCustomer = async () => {
  if (data.value.source == 'clue') {
    await ElMessageBox.confirm(`确定将【${customerInfo.value.name}】转化为客户吗？`)
    await ClueApi.transformClue(data.value.sourceId)
    ElMessage.success(`转化客户【${customerInfo.value.name}】成功`)
  } else if (data.value.source == 'ent') {
    customerFormRef.value.openByEnt(data.value.sourceId, data.value.callee)
  }
}
/**修改标签*/
const setTag = async () => {
  if (data.value.source == 'clue') {
    const results = await ClueApi.getClueTag({ ids: [data.value.sourceId] })
    let clueTag = []
    if (Object.keys(results).length) {
      clueTag = results[data.value.sourceId]
    }
    editTagForm.value.open('update', data.value.sourceId, clueTag)
  } else if (data.value.source == 'customer') {
    const results = await CustomerApi.getCustomerTag({ ids: [data.value.sourceId] })
    let customerTag = []
    if (Object.keys(results).length) {
      customerTag = results[data.value.sourceId]
    }
    editTagCustomerForm.value.open('update', data.value.sourceId, customerTag)
  } else if (data.value.source == 'ent') {
    editTagEnt.value.open('update', data.value.sourceId, [])
  }
}
// Add param: number -> by PetePower
const saveFollow = async () => {
  const res = await AgentApi.addFollowRecord({
    reqNo: reqNo.value,
    content: followUp.value,
    nextTime: nextTime.value,
    number: number.value
  })
  if (res) {
    message.success('已保存跟进内容！')
    followUp.value = ''
    nextTime.value = ''
    customerInfo.value = await AgentApi.getCustomerInfo({ reqNo: reqNo.value })
  }
}

const close = () => {
  dialogVisible.value = false
  followUp.value = ''
  nextTime.value = ''
}

const onHangup = () => {
  WebPhone.getInstance().hangup()
}

const showHangup = computed(() => {
  if (!data.value) {
    return false
  }
  return (
    data.value.status == 'ringing' ||
    data.value.status == 'progress' ||
    data.value.status == 'accepted'
  )
})
// 播放音频
const playAudio = () => {
  audio.value?.play()
}
// 暂停音频
const pauseAudio = () => {
  audio.value?.pause()
}
// watch(
//   () => data.value,
//   (value) => {
//     log.error('状态', JSON.stringify(value))
//     if (value) {
//       if (value.status == 'ringing' || value.status == 'progress') {
//         playAudio()
//       }
//       if (value.status == 'failed' || value.status == 'accepted' || value.status == 'ended') {
//         pauseAudio()
//       }
//     }
//   },
//   { immediate: true, deep: true }
// )

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗
</script>
<style>
.callTipDialogDiv .el-overlay-dialog {
  pointer-events: none;
}

.callTipDialogDiv .el-dialog {
  margin-right: 20px;
  pointer-events: auto;
  background: linear-gradient(to bottom, #98b0ec, #d0d5fe);
  border-radius: 10px;
}

.callTipDialogDiv .el-overlay-dialog {
  right: 18px;
}

.callTipDialogDiv > div:first-of-type {
  inset: inherit !important;
}
</style>
<style scoped lang="scss">
.phone-icon-box {
  display: flex;
  height: 16px;
  padding: 2px 10px;
  color: white;
  background: var(--el-color-primary);
  border-radius: 4px;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  font-size: 12px;
}
::v-deep .el-descriptions__cell {
  padding-bottom: 0 !important;
}

.card-btn {
  margin: 4px;
  text-align: center;
  .el-button {
    width: 100%;
    span {
      font-size: 14px;
    }
  }
}
.card-btns {
  margin: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-button {
    width: 49%;
    span {
      font-size: 14px;
    }
  }
}
.customer-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.callTipDialogDiv {
  ::v-deep(.el-dialog__body) {
    padding: 4px 10px;
  }

  ::v-deep(.el-dialog__header) {
    padding-top: 10px;
    margin-right: 0;
    background: #ecf0f390;
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
  }

  .content {
    background: #ffffff83;
  }

  .transparent {
    ::v-deep(.el-descriptions__body) {
      color: #fff;
      background: transparent;
    }
  }

  ::v-deep(.el-textarea__inner::-webkit-scrollbar) {
    display: none;
  }

  ::v-deep(.el-textarea__inner) {
    padding-bottom: 30px;
    background: rgba($color: #fff, $alpha: 80%);
  }

  ::v-deep(.el-descriptions__content:not(.is-bordered-label)),
  ::v-deep(.el-descriptions__label:not(.is-bordered-label)) {
    font-size: 12px;
  }
}
</style>
